<template>
  <basic-container>
    <avue-crud
      :option="option"
      :search.sync="search"
      :table-loading="loading"
      :data="data"
      :page.sync="page"
      :permission="permissionList"
      :before-open="beforeOpen"
      v-model="form"
      ref="crud"
      @row-update="rowUpdate"
      @row-save="rowSave"
      @row-del="rowDel"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @sort-change="sortChange"
      @on-load="onLoad"
    >
      <template slot-scope="scope" slot="menu">
        <el-button icon="el-icon-edit" size="small" type="text" v-if="permission.merchant_menu_edit" @click.stop="handleMenu(scope.row, scope.index)">编 辑</el-button>
      </template>
      <!-- <template slot-scope="scope" slot="menu">
        <el-button
          v-if="permission.merchant_menu_view"
          icon="el-icon-view"
          size="small"
          type="text"
          @click.stop="handleDetail(scope.row, scope.index)"
          >详 情</el-button
        >
        <el-button
          v-if="permissionList.editBtn && scope.row.rpiExStatus == -1"
          icon="el-icon-edit"
          size="small"
          type="text"
          @click.stop="handleEdit(scope.row, scope.index)"
          >编 辑</el-button
        >
        <el-button
          v-if="permissionList.editBtn && scope.row.rpiExStatus == '4'"
          icon="el-icon-edit"
          size="small"
          type="text"
          @click.stop="handleAuditEdit(scope.row, scope.index)"
          >编 辑</el-button
        >
      </template> -->
      <!-- <template slot="menuLeft">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="small"
          @click.stop="handleSave"
          >新 增</el-button
        >
        <el-button
          type="danger"
          size="small"
          icon="el-icon-delete"
          plain
          v-if="permission.pos_info_delete"
          @click="handleDelete"
          >删 除
        </el-button>
      </template> -->
    </avue-crud>
    <el-dialog title="菜单分配"
               append-to-body
               :visible.sync="dialogMenuVisible"
               width="450px">
      <menu-grant ref="toMenuGrant" />
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="dialogMenuVisible = false">取 消</el-button>
        <el-button size="small" type="primary" v-preventClick @click="menuSubmit">确 定</el-button>
      </span>
    </el-dialog>
  </basic-container>
</template>

<script>
import {
  getDetail,
  add,
  update,
  remove,
  getMerchantRole,
  updateMerchantRole
} from "@/api/rb-oem/posinfo/pos_info";
import { mapGetters } from "vuex";
import menuGrant from '@/components/rb-service/menu-grant';


export default {
  components: {
    menuGrant
  },
  data() {
    return {
      form: {},
      query: {},
      search: {},
      active: 0,
      openType: "", //打开dialog弹框的类型
      roleId: null, //角色id
      userType: "3",
      dialogMenuVisible: false,
      props: {
        //菜单权限数据 props
        label: "title",
        value: "key",
        disabled: this.isDisabledFn,
      },
      loading: true,
      excelBox: false,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0,
      },
      selectionList: [],
      option: {
        height: "calc(50vh - 50px)",
        calcHeight: 30,
        tip: false,
        border: true,
        index: true,
        selection: true,
        searchMenuSpan: 6,
        columnBtn: false,
        addBtn: false,
        editBtn: false,
        delBtn: false,
        column: [
          {
            label: "主键",
            prop: "id",
            type: "input",
            sortable: true,
            addDisplay: false,
            editDisplay: false,
            viewDisplay: false,
            hide: true,
            overHidden: true,
          },
          {
            label: "用户编号",
            prop: "userNo",
            type: "input",
            sortable: true,
            display: false,
            hide: true,
            overHidden: true,
          },
          {
            label: "菜单名称",
            prop: "roleName",
            type: "select",
            // dicUrl: "/api/blade-system/dict/dictionary?code=merchant_role_type",
            // props: {
            //   label: "dictValue",
            //   value: "dictKey",
            // },
            // dataType: "string",
            // search: true,
            rules: [
              {
                required: true,
                message: "请输入菜单名称",
                trigger: "blur",
              },
            ],
            overHidden: true,
          },
        ],
      },
      data: [],
    };
  },
  computed: {
    ...mapGetters(["permission"]),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.merchant_menu_add, false),
        viewBtn: this.vaildData(this.permission.merchant_menu_view, false),
        delBtn: this.vaildData(this.permission.merchant_menu_delete, false),
        editBtn: this.vaildData(this.permission.merchant_menu_edit, false),
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids.join(",");
    },
  },
  created() {
  },
  methods: {
    /**
     * @func 菜单分配
     * @desc 点击编辑回显基本信息
     * @param {Object} row - 表格绑定的信息
     * */
    handleMenu(row) {
      this.dialogMenuVisible = true;
      this.roleId = row.id;
      this.$nextTick(() => {
        this.$refs["toMenuGrant"].getMenuGrant("merchantMenu", "3", {"userId": row.id});
      })
    },
    /**
     * @func 提交菜单
     * @desc 提交编辑后的菜单
     * */
    menuSubmit() {
      const menuList = this.$refs["toMenuGrant"].$refs.treeMenu.getCheckedKeys();
      const menudata = {
        "roleId": this.roleId,
        "menuIds": menuList
      }
      updateMerchantRole(menudata).then((res) => {
        if (res.data.code == '200') {
          this.dialogMenuVisible = false;
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        } else {
          this.$message({
            type: "error",
            message: res.data.message
          });
        }
      }, error => {
        window.console.log(error);
      });
    },
    rowSave(row, done, loading) {
      add(row).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!",
          });
          done();
        },
        (error) => {
          loading();
          window.console.log(error);
        }
      );
    },
    rowUpdate(row, index, done, loading) {
      update(row).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!",
          });
          done();
        },
        (error) => {
          loading();
          window.console.log(error);
        }
      );
    },
    rowDel(row) {
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!",
          });
        });
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!",
          });
          this.$refs.crud.toggleSelection();
        });
    },
    beforeOpen(done, type) {
      this.openType = type;
      if (["edit", "view"].includes(type)) {
        getDetail(this.form.id).then((res) => {
          this.form = res.data.data;
        });
      }
      done();
    },
    /**
     * @func 菜单权限树形是否禁止
     * @desc dialog打开类型为 view 则禁止权限树
     * @param {String} openType - 打开类型
     * */
    isDisabledFn() {
      const _this = this;
      if (["view"].includes(_this.openType)) {
        return true;
      }
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      getMerchantRole(
        page.currentPage,
        page.pageSize,
        Object.assign(params, this.query)
      ).then((res) => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data;
        this.loading = false;
        this.selectionClear();
      });
    },
    sortChange(val) {
      if (val.order == "ascending") {
        //正序
        this.query.ascs = val.prop;
        this.query.descs = "";
      } else {
        //倒序
        this.query.descs = val.prop;
        this.query.ascs = "";
      }
      this.refreshChange();
    },
  },
};
</script>

<style>
</style>
